<?php
/**
 * @author spenceryg
 * @date 2022/11/25
 * @time 1:03 下午
 * @focus love & life
 */

namespace app\admin\controller\sys\business;

use app\admin\controller\sys\model\AdminNodeModel;
use app\admin\controller\sys\validate\AdminNodeValidate;

class AdminNodeBusiness
{
    public static function getList($where = [], $order = 'sort asc,id asc')
    {
        return AdminNodeModel::where($where)->order($order)->select();
    }


    public static function add($data)
    {
        validate(AdminNodeValidate::class)->check($data);
        $adminNode = AdminNodeModel::create($data);
        $adminNode->level = AdminNodeModel::getLevel($adminNode);
        if (!$adminNode->sort) {
            $adminNode->sort = AdminNodeModel::getSort($adminNode);
        }
        $adminNode->save();
        return $adminNode->id;
    }



    public static function update($data)
    {
        validate(AdminNodeValidate::class)->check($data);
        $old_pid = AdminNodeModel::where('id', $data['id'])->value('pid');
        $adminNode = AdminNodeModel::update($data);
        $adminNode->level = AdminNodeModel::getLevel($adminNode);
        if (!$adminNode->sort || $old_pid != $data['pid']) {
            $adminNode->sort = AdminNodeModel::getSort($adminNode);
        }
        $adminNode->save();
        return $adminNode->id;
    }


    /**
     * 获取树状结构
     * @param $menu_id_arr
     * @return array
     */
    public static function getTree($menu_id_arr): array
    {
        $where = [];
        $where[] = ['is_show', '=', 1];
        if ($menu_id_arr != '*') {
            $where[] = ['id', 'in', $menu_id_arr];
        }
        $data = self::getList($where);
        $key_data = [];
        foreach ($data as $v) {
            $pid = $v->getData('pid');
            $v = $v->toArray();
            $v['pid'] = $pid;
            $key_data[$v['id']] = $v;
        }
        $tree = [];

        foreach ($key_data as $k=>$v) {
            if ($v['pid']) {
                $key_data[$v['pid']]['son'][] = &$key_data[$k];
            } else {
                $tree[] = &$key_data[$k];
            }
        }
        return $tree;
    }
}
